package com.pr.makfilm.dao.impl;

import com.pr.makfilm.dao.ISchoolDao;
import com.pr.makfilm.domain.*;
import com.pr.makfilm.domain.filter.AbstractFilter;
import com.pr.makfilm.domain.filter.SchoolFilter;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Pawel
 * Date: 10.09.13
 * Time: 22:53
 * To change this template use File | Settings | File Templates.
 */
@Repository(SchoolDaoImpl.BEAN_NAME)
public class SchoolDaoImpl extends AbstractDaoImpl<School> implements ISchoolDao
{
   public static final String BEAN_NAME = "schoolDao";

   @Override
   public List<School> findByType(SchoolType type, User user)
   {
      Criteria criteria = createCriteria();
      criteria.add(Restrictions.eq(School.FIELD_TYPE, type));
      criteria.add(Restrictions.eq(School.FIELD_USER, user));
      criteria.add(Restrictions.eq(School.FIELD_OBJECT_STATE, ObjectStateEnum.ACTIVE));
      return criteria.list();
   }

   @Override
   public List<String> findSchoolCities(User user)
   {
      Criteria criteria = createCriteria();
      criteria.add(Restrictions.eq(School.FIELD_USER, user));
      criteria.add(Restrictions.eq(School.FIELD_OBJECT_STATE, ObjectStateEnum.ACTIVE));
      criteria.setProjection(Projections.distinct(Projections.property(School.FIELD_CITY)));
      return criteria.list();
   }

   @Override
   public Criteria createCriteriaFromSearchParams(AbstractFilter abstractFilter)
   {
      Criteria criteria = createCriteria();
      SchoolFilter filter = (SchoolFilter) abstractFilter;
      User user = filter.getUser();
      if (user != null)
      {
         criteria.add(Restrictions.eq(School.FIELD_USER, user));
      }
      String name = filter.getName();
      if (name != null)
      {
         criteria.add(Restrictions.ilike(School.FIELD_NAME, name, MatchMode.ANYWHERE));
      }
      District district = filter.getDistrict();
      if (district != null)
      {
         criteria.add(Restrictions.eq(School.FIELD_DISTRICT, district));
      }
      criteria.add(Restrictions.eq(School.FIELD_OBJECT_STATE, ObjectStateEnum.ACTIVE));
      return criteria;
   }
}
